package nl.samenloop.bigscreen.clock;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Calendar;

import javax.swing.JLabel;

import nl.samenloop.bigscreen.Constants;
import nl.samenloop.bigscreen.fx.Transparency;

/**
 * 
 * @author Bram Wiekens
 * 
 */
@SuppressWarnings("serial")
public class CountdownClock extends JLabel implements Transparency {

	private static long DAY = 24 * 3600000;
	private static long HOUR = 3600000;
	private static long MINUTE = 60000;
	private static long SECOND = 1000;
	private long start;

	private static String TEST_STR = "00:00:00";

	private float opacity = 0.0f;

	
	public CountdownClock() {
		//parent = getJFrameParent();
		
		setDoubleBuffered(true);
		
		setIgnoreRepaint(true);

		setText(TEST_STR);

		Font f = new Font("Droid Sans", Font.BOLD, 80);
		setForeground(Color.black);

		setFont(f);

		setText(TEST_STR);
		startUpdateThread();
	}

	public void setStart(long start) {
		this.start = start;
	}
	
	public void paint(Graphics g) {
		if (g != null) {
			Graphics2D g2 = (Graphics2D) g.create();
			g2.setBackground(Constants.TRANSPARANT);
			g2.clearRect(0, 0, getWidth(), getHeight());

			g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));

			super.paint(g2);

			g2.dispose();
		}

	}

	public void startUpdateThread() {
		Thread updater = new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					setText(updateClock());
					try {
						Thread.sleep(1000);

					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					invalidate();
				}
			}
		});

		updater.start();
	}

	private String prepend(long num) {
		return num < 10 ? "0" + num : "" + num;
	}

	private String setClock(long days, long hours, long minutes, long seconds) {
		String dayStr = days > 0 ? days + " dagen " : "";
		String time = "";

		time = dayStr + prepend(hours) + ":" + prepend(minutes) + ":" + prepend(seconds);

		return time;
	}

	private String updateClock() {
		long now = Calendar.getInstance().getTimeInMillis();

		long diff = start - now > 0 ? start - now : 0;

		long days = diff / DAY;

		diff = diff - (days * DAY);

		long hours = diff / HOUR;

		diff = diff - (hours * HOUR);

		long minutes = diff / MINUTE;

		diff = diff - (minutes * MINUTE);

		long seconds = diff / SECOND;

		return setClock(days, hours, minutes, seconds);
	}


	@Override
	public float getOpacity() {
		return opacity;
	}


	@Override
	public void setOpacity(float opacity) {
		this.opacity = opacity;
	}

}
